package com.lujieni.springbootsecurity.filter;

import com.lujieni.springbootsecurity.dao.UserMapper;
import com.lujieni.springbootsecurity.po.UserDO;
import com.lujieni.springbootsecurity.utils.JWTUtils;
import com.lujieni.springbootsecurity.utils.SecurityFrameworkUtils;
import lombok.RequiredArgsConstructor;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.security.core.userdetails.UsernameNotFoundException;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @Author：小鹿爱吃鱼
 * @Date: 2025/5/29 15:44
 * @Description:
 */
@RequiredArgsConstructor
public class JwtAuthenticationFilter extends OncePerRequestFilter {

    private final JWTUtils jwtUtils;

    private final UserMapper userMapper;

    private final RedisTemplate<String, String> redisTemplate;

    private static final String REDIS_TOKEN_KEY = "login-token:%s:%s";


    @Override
    protected void doFilterInternal(HttpServletRequest request, HttpServletResponse response, FilterChain filterChain) throws ServletException, IOException {
        if(!StringUtils.hasText(request.getHeader("token"))){
            filterChain.doFilter(request, response);
            return;
        }
        // 校验token的合法性
        String userId = null;
        userId = jwtUtils.getClaimFromToken(request.getHeader("token"));
        if(!StringUtils.hasText(userId)){
            throw new UsernameNotFoundException("非法的token");
        }
        // 对应的userId 数据库里要有
        UserDO sysUserDO = userMapper.selectById(Long.valueOf(userId));
        if(sysUserDO != null && redisTemplate.hasKey(String.format(REDIS_TOKEN_KEY, userId, request.getHeader("token")))){
            // 传入的token必须和redis里存的一致
            SecurityFrameworkUtils.setLoginUser(sysUserDO);
        }
        // 继续过滤器链
        filterChain.doFilter(request, response);
        /*
            SecurityContextPersistenceFilter会最先执行,里面会有对SecurityContextHolder的清理工作
         */
    }
}
